import router from "./router";
import store from "./store";
import { Message } from "element-ui";
import NProgress from "nprogress"; // progress bar
import "nprogress/nprogress.css"; // progress bar style
// import { getToken } from "@/utils/auth"; // get token from cookie
// import getPageTitle from "@/utils/get-page-title";
//引入动态路由数组
import { asyncRoutes } from "@/router";

//白名单
const whiteList = ["/login", "/404"]; // no redirect whitelist

// 前置路由守卫
router.beforeEach(async (to, from, next) => {
  // 启动进度条
  NProgress.start();
  //判断是否有token，做鉴权操作
  if (store.getters.token) {
    //如果在登录页，直接去首页
    if (to.path === "/login") {
      next("/");
      NProgress.done();
    } else {
      //获取用户信息
      //如果没有用户信息，则去获取用户
      if (!store.getters.userId) {
        const { roles } = await store.dispatch("user/getInfo");
        //过滤当前用户匹配的权限
        const filterRoute = asyncRoutes.filter((item) => {
          return roles.menus.includes(item.name);
        });

        //将匹配的路由结果保存到vuex中
        store.commit("user/setRoute", filterRoute);
        //将匹配的路由添加到路由表中
        router.addRoutes([
          ...filterRoute,
          { path: "*", redirect: "/404", hidden: true },
        ]);
      }
      next();
    }
    //否则旅行
  } else {
    //没有登录
    //判断是否在白名单，如果在也直接放行，不在则去登录页
    if (whiteList.includes(to.path)) {
      next();
    } else {
      next("/login");
      Message.error("无效token");
      return Promise.reject("无效token");
    }
  }
});

// 后置路由，页面加载完后
router.afterEach(() => {
  // 结束进度条
  NProgress.done();
});
